<!DOCTYPE html>
<html lang="en">
  <body>
    <div>
      <button type="button" onclick="method1()">防抖</button>
      <button type="button" onclick="method2()">节流</button>
    </div>
    <script type="text/javascript">
      antiShake = function (func, wait, immediate) {
        let timeout;
        return function () {
          // 取消 setTimeout 的定时操作
          clearTimeout(timeout);
          if (immediate) {
            // 立即执行
            let callNow = !timeout;
            timeout = setTimeout(function () {
              timeout = null;
            }, wait);
            if (callNow) {
              func();
            }
          } else {
            timeout = setTimeout(func(), wait);
          }
        };
      };
      method1 = antiShake(
        function () {
          console.log("点击事件");
        },
        5000,
        true
      );

      // 节流
      throtter = function (cd, time = 3000) {
        var t = null;
        return function () {
          if (t) return;
          t = setTimeout(function () {
            cd.call(this);
            t = null;
          }, time);
        };
      };
      method2 = throtter(function () {
        console.log("节流");
      });
    </script>
  </body>
</html>
